 
#include "../Headers/dis_img_pro.h"
pthread_mutex_t db_mutex;
int exitPipe[2];//主进程通知子进程退出管道
void sigFunc_user(int signum){
    printf("signum = %d\n",signum);
    write(exitPipe[1],"1",1);
    printf("Parent process is going to die!\n");
}
void sigFunc_c(int signum){
    printf("signum = %d\n",signum);
    write(exitPipe[1],"1",1);
    printf("Parent process is going to die!\n");
}    
int main(int argc, char *argv[]){  
    // ./main  port num_tids
    ARGS_CHECK(argc,3); 
    int ret = pipe(exitPipe);
    ERROR_CHECK(-1,ret,"pipe");
   
    if(fork()!= 0){
        close (exitPipe[0]);
        signal(SIGUSR1,sigFunc_user);
        signal(SIGINT,sigFunc_c);
        wait(NULL);
        exit(0);
    }
    
    close(exitPipe[1]);
    
    int worker_num = atoi(argv[2]);
    threadPool thread_pool;//tid,taskqueue 初始化
    
    threadPoolInit(&thread_pool,worker_num);//初始化线程池内存
    pthread_mutex_init(&db_mutex,NULL);
    makeWorker(&thread_pool);//创建若干个子线程；
    int sock_fd = tcp_init("0",atoi(argv[1]),50);
    ERROR_CHECK(sock_fd,-1,"tcp_init");
    //epoll
    int epfd = epoll_create(1);
    epollAdd(sock_fd,epfd);
    epollAdd(exitPipe[0],epfd);
    struct epoll_event readyArr[10];

    while (1)   
    {
        int ready_num = epoll_wait(epfd,readyArr,10,-1);
        ERROR_CHECK(ready_num,-1,"epoll_wait");
        printf("epoll_wait returns\n");
        for (size_t i = 0; i < ready_num; i++)
        {
            int ready_fd = readyArr[i].data.fd;
            if (ready_fd == sock_fd)
            {
                int net_fd = tcp_wait(sock_fd);
                //加锁
                pthread_mutex_lock(&thread_pool.taskQueue.mutex);
                
                taskEnqueue(&thread_pool.task_online,net_fd);
                taskEnqueue(&thread_pool.taskQueue,net_fd);//生产一个任务
                printf("New task!--%d\n",ready_fd);
                pthread_cond_signal(&thread_pool.taskQueue.cond);//通知处于唤醒队列的线程
                pthread_mutex_unlock(&thread_pool.taskQueue.mutex);

            }else if(ready_fd == exitPipe[0]){
                printf("child process,threadPool is going to die\n");
                thread_pool.exitFlag = 1;
                pthread_cond_broadcast(&thread_pool.taskQueue.cond);
                for (size_t i = 0; i < worker_num; i++)
                {
                    pthread_join(thread_pool.pTid[i],NULL);
                }
                pthread_exit(NULL); 
            }
            
        }
        
    } 
}
